package com.xiaolv.web.config;

import lombok.SneakyThrows;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.text.ParseException;
import java.util.Collection;

/**
 * 日期精确分片
 *
 * @author lvlinguang
 * @date 2020-08-10 19:11
 */
public class DayShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    /**
     * 设置分片
     *
     * @param tableNames    数据表
     * @param shardingValue 分片列信息
     * @return
     */
    @SneakyThrows
    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<String> shardingValue) {
        String tableName = shardingValue.getLogicTableName();
        String key = getDate(shardingValue.getValue(), 8);
        return tableName.concat("_").concat(key);
    }

    /**
     * 得到日期数字
     *
     * @param date 字符串日期
     * @param len  长度
     * @return 202008
     * @throws ParseException
     */
    public String getDate(String date, int len) throws ParseException {
        String number = date.replaceAll("\\D", "");
        return number.substring(0, len);
    }
}
